package com.mvc.controller;

import com.mvc.entity.User;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * Created by zhudong on 2016/8/2.
 */
@Controller
public class HelloController {
    private final static String SUCCESS = "success";

    @RequestMapping("/hello")
    public String hello(){
        System.out.printf("hello spring mvc");
        return "success";
    }

    @RequestMapping("/testPojo")
    public String testPojo(User user){
        System.out.printf("user:"+user);
        return "success";
    }

    @ModelAttribute
    public void getUser(@RequestParam(value = "id",required = false)Integer id,
                        Map<String,Object> map){
        if(id != null){
//            User user = new User("zeus",1,"123456","yuzhou346694246@126.com",12);
//            System.out.printf("数据库中的对象:"+user);
//            map.put("user",user);
        }
    }

    @RequestMapping("/testModelAttribute")
    public String testModelAttribute(User user){
        System.out.printf("修改:"+user);
        return "success";
    }

    @RequestMapping("/testMap")
    public String testMap(Map<String,Object> map){
        map.put("name", "dongge");
        return SUCCESS;
    }

    @ExceptionHandler({RuntimeException.class})
    public String handleEx(Exception ex,Map<String,Object> map){
        map.put("ex",ex);
        return "error";
    }

    @RequestMapping("/testException")
    public String testException(){
        System.out.println(1 / 0);
        return SUCCESS;
    }

    @RequestMapping(value = "/fileupload",method = RequestMethod.POST)
    public String upload(@RequestParam("name") String name,
                         @RequestParam("file")MultipartFile file) throws IOException{
        System.out.println("fileName:"+name);
        System.out.println("file:"+file.getBytes());
        System.out.println("fileName:"+file.getName());
        System.out.println("OriginalFileName:"+file.getOriginalFilename());
        String content = new String(file.getBytes());
        System.out.println(content);
        return "success";
    }

    @RequestMapping(value = "/multifileupload",method = RequestMethod.POST)
    public String multiUpload(@RequestParam("name") String name,
                              @RequestParam("file") MultipartFile [] files)
            throws IOException
    {
        System.out.println("文件数量:"+files.length);
        for (MultipartFile file:files){
            System.out.println("文件名:"+file.getOriginalFilename());
            System.out.println("内容:"+new String(file.getBytes()));
        }
        return SUCCESS;
    }
}
